<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="属性名称" prop="attributeName">
        <el-input
          v-model="queryParams.attributeName"
          placeholder="请输入属性名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="属性类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择属性类型" clearable size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['goods:attribute:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['goods:attribute:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['goods:attribute:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="attributeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="商户ID" align="center" prop="extAppid" />
      <el-table-column label="商品ID" align="center" prop="goodsId" />-->
      <el-table-column label="属性名称" align="center" prop="attributeName" />
      <el-table-column label="默认值" align="center" prop="defaultValue" />
      <el-table-column label="属性类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="typeOptions" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="属性启用状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="排序号" align="center" prop="sort" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.type == '0'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleOptionList(scope.row)"
            v-hasPermi="['goods:attribute:edit']"
          >编辑选项</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['goods:attribute:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['goods:attribute:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品属性对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="属性名称" prop="attributeName">
          <el-input v-model="form.attributeName" placeholder="请输入属性名称" />
        </el-form-item>
        <el-form-item label="默认值" prop="defaultValue">
          <el-input v-model="form.defaultValue" placeholder="请输入默认值" />
        </el-form-item>
        <el-form-item label="属性类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择属性类型" style="width: 100%">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="启用状态">
          <el-radio-group v-model="form.status" >
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序号" prop="sort">
          <el-input-number :min="0" v-model="form.sort" placeholder="请输入排序号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 编辑选项对话框 -->
    <el-dialog :title="optionTitle" :visible.sync="optionOpen" width="800px" append-to-body>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleOptionAdd"
          >新增</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="loading" :data="optionList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="选项名称" align="center" prop="optionName" />
        <el-table-column label="排序号" align="center" prop="sort" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleOptionUpdate(scope.row)"
              v-hasPermi="['goods:option:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleOptionDelete(scope.row)"
              v-hasPermi="['goods:option:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="optionTotal>0"
        :total="optionTotal"
        :page.sync="queryOptionParams.pageNum"
        :limit.sync="queryOptionParams.pageSize"
        @pagination="getOptionList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改属性选项对话框 -->
    <el-dialog :title="title" :visible.sync="optionDialog" width="500px" append-to-body>
      <el-form ref="optionForm" :model="optionForm" :rules="rules" label-width="80px">
        <el-form-item label="选项名称" prop="optionName">
          <el-input v-model="optionForm.optionName" placeholder="请输入选项名称" />
        </el-form-item>
        <el-form-item label="排序号" prop="sort">
          <el-input-number v-model="optionForm.sort" placeholder="请输入排序号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitOptionForm">确 定</el-button>
        <el-button @click="optionCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listAttribute,
  getAttribute,
  delAttribute,
  addAttribute,
  updateAttribute,
  changeAttributeStatus
} from "@/api/goods/attribute";
import {addOption, delOption, getOption, listOption, updateOption} from "@/api/goods/option";

export default {
  name: "Attribute",
  data() {
    return {
      // 遮罩层
      loading: true,
      optionLoading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品属性表格数据
      attributeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      optionTotal: 0,
      //选项表格数据
      optionList:[],
      // 弹出层标题
      optionTitle: "",
      // 是否显示弹出层
      optionOpen: false,

      optionDialog :false,
      // 0为下拉选择；1为文本；2为日期选择；3为时间选择；4为日期范围；5为时间范围；6为开关选项字典
      typeOptions: [],
      // 属性启用状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        attributeName: null,
        type: null
      },
      // 表单参数
      form: {},

      // 查询参数
      queryOptionParams: {
        pageNum: 1,
        pageSize: 10,
        attributeId: null
      },

      optionForm:{},
      // 表单校验
      rules: {
        attributeName: [
          { required: true, message: "属性名称不能为空", trigger: "blur" },
          { max: 20, message: '属性名称长度不能超过20个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: "属性类型不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "属性启用状态不能为空", trigger: "blur" }
        ],
        optionName: [
          { required: true, message: "选项名称不能为空", trigger: "blur" },
          { max: 20, message: '选项名称长度不能超过20个字符', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: "排序号不能为空", trigger: "blur" },
          { pattern: /^[0-9]\d*$/, message: "排序号必须为正整数", trigger: "blur" },
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("attribute_type").then(response => {
      this.typeOptions = response.data;
    });
    this.getDicts("store_common_status").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询商品属性列表 */
    getList() {
      this.loading = true;
      listAttribute(this.queryParams).then(response => {
        this.attributeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.optionOpen = false;
      this.reset();
    },
    // 取消按钮
    optionCancel() {
      this.optionDialog = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        extAppid: null,
        goodsId: null,
        attributeName: null,
        defaultValue: null,
        type: null,
        status: "0",
        sort: null
      };
      this.resetForm("form");
      this.optionForm = {
        id: null,
        extAppid: null,
        attributeId: null,
        optionName: null,
        sort: null
      };
      this.resetForm("optionForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品属性";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAttribute(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品属性";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAttribute(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAttribute(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除商品属性编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delAttribute(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 更改状态 */
    handleStatusChange(row){
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.attributeName + '"属性吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return changeAttributeStatus(row.id, row.status);
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    handleOptionList(row){
      this.optionTitle = row.attributeName+'--选项编辑';
      this.optionOpen = true;
      this.queryOptionParams.attributeId=row.id;
      this.getOptionList();
    },
    getOptionList() {
      this.optionLoading = true;
      listOption(this.queryOptionParams).then(response => {
        this.optionList = response.rows;
        this.optionTotal = response.total;
        this.optionLoading = false;
      });
    },
    /** 新增按钮操作 */
    handleOptionAdd() {
      this.reset();
      this.optionDialog = true;
      this.title = "添加属性选项";
    },
    /** 修改按钮操作 */
    handleOptionUpdate(row) {
      this.reset();
      const id = row.id;
      getOption(id).then(response => {
        this.optionForm = response.data;
        this.optionDialog = true;
        this.title = "修改属性选项";
      });
    },
    /** 提交按钮 */
    submitOptionForm() {
      this.$refs["optionForm"].validate(valid => {
        if (valid) {
          if (this.optionForm.id != null) {
            updateOption(this.optionForm).then(response => {
              this.msgSuccess("修改成功");
              this.optionDialog = false;
              this.getOptionList();
            });
          } else {
            this.optionForm.attributeId = this.queryOptionParams.attributeId;
            addOption(this.optionForm).then(response => {
              this.msgSuccess("新增成功");
              this.optionDialog = false;
              this.getOptionList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleOptionDelete(row) {
      const ids = row.id
      this.$confirm('是否确认删除"' + row.optionName + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delOption(ids);
      }).then(() => {
        this.getOptionList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
  }
};
</script>
